//
//  UPShopingCart.m
//  LoveFreshBee
//
//  Created by wyzc on 16/6/16.
//  Copyright © 2016年 叶落知秋. All rights reserved.
//

#import "UPShopingCart.h"
#import "UPShopingCartMOdel.h"

@implementation UPShopingCart

//单例
static id _instance;

+(instancetype)allocWithZone:(struct _NSZone *)zone
{
    if (_instance==nil) {
        static dispatch_once_t oneToken;
        dispatch_once(&oneToken, ^{
            _instance=[super allocWithZone:zone];
        });
    }
    return _instance;
}

+(instancetype)sharedCart
{
    if (_instance==nil) {
        _instance=[[self alloc] init];
    }
    return _instance;
}

-(instancetype)init
{
    if (self=[super init]) {
        _cart=[NSMutableArray array];
    }
    return self;
}



/**
 *  添加商品到购物车
 */

-(void)addToCart:(UPShopingCartMOdel *)cartModel
{
    //1.先判断购物车中是否已经存在该商品了，存在的话更新数量，不存在的话，添加商品
    for (UPShopingCartMOdel *model in _cart) {
        if (model.iid==cartModel.iid) {
            model.num+=1;
            return;
        }
    }
    [self.cart addObject:cartModel];
    
}
/**
 *  从购物车移除某个商品
 */
-(void)removeFromCart:(int)iid
{
    for (UPShopingCartMOdel *model in _cart) {
        if (model.iid==iid) {
            model.num--;
            if (model.num==0) {
                [_cart removeObject:model];
            }
        }
    }
    
}




@end
